<?php
session_start();
require('mysqli_connect.php');
require('functions.php');
//User Validation...
if(isset($_COOKIE['ID']) && isset($_SESSION['ID']) && isset($_COOKIE['USER'])) { //it's mandatory to have all this variables set to validate, and continue with the page, Login set all this vars
	$user = validation1($_COOKIE['USER'], $_COOKIE['ID'], $_SESSION['ID'], $dbc);
	if(is_array($user)) { //validation done (correct)
		$webpage = '/timetables/files/timetables.php';
		$sections = array();
		$sections[] = 'share';
		$ev = mysqli_real_escape_string($dbc, $_POST['ev']);
		$shuser = mysqli_real_escape_string($dbc, $_POST['shuser']);
		//validate the ownership of the event with the logged user
		$q = "select * from share where (idevent=".$ev." and iduser=".$user['iduser']." and owner=".$user['iduser'].")";
		$r = @mysqli_query ($dbc, $q);
		$existev = mysqli_fetch_array($r, MYSQLI_ASSOC);

		//validate that exist the user i want to share the event with
		$q = "select * from users where iduser=".$shuser;
		$r = @mysqli_query ($dbc, $q);
		$existus = mysqli_fetch_array($r, MYSQLI_ASSOC);

		//check if the event is already shared with the shuser
		$q = "select * from share where (idevent=".$ev." and iduser=".$shuser." and owner=".$user['iduser'].")";
		$r = @mysqli_query ($dbc, $q);
		$shared = mysqli_fetch_array($r, MYSQLI_ASSOC);

		if($shared) {
			
			//UNSHARE
			$q = "delete from share where (idevent=".$ev." and iduser=".$shuser." and owner=".$user['iduser'].")";
			$r = @mysqli_query ($dbc, $q);
		}
		else {

			//SHARE!
			$q = "insert into share(idevent, iduser, owner) values (".$existev['idevent'].", ".$existus['iduser'].", ".$existev['owner'].")";
			$r = @mysqli_query ($dbc, $q);
		}

		header('Location: ' .$webpage. '?curr='.$sections[0].'&ev='.$ev);
	}
	else{
		$_SESSION['ID']= 'BANNED';
		header('Location: noob.htm');
	}
}
?>